package cn.xny.user.service.impl;

import cn.xny.basic.exception.BusinessException;
import cn.xny.basic.util.Md5Utils;
import cn.xny.basic.util.StrUtils;

import cn.xny.user.domain.Logininfo;
import cn.xny.user.domain.User;
import cn.xny.user.mapper.LogininfoMapper;
import cn.xny.user.mapper.UserMapper;
import cn.xny.user.service.UserService;
import cn.xny.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private   LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Transactional
    @Override
    public void save(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //先添加logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);//获取到自增ID

        //添加user的数据
        user.setLogininfoId(logininfo.getId());
        super.save(user);
    }
    @Transactional
    @Override
    public void del(Long id) {
        //先查询登陆信息id
        User user = userMapper.loadByAll(id);

        //删除logininfo
        logininfoMapper.del(user.getLogininfoId());
        //删除user
        super.del(id);



    }
    @Transactional
    @Override
    public void update(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        User oldUser = userMapper.loadByAll(user.getId());//loginfo_id

        //修改user信息
        user.setLogininfoId(oldUser.getLogininfoId());
        super.update(user);
        //修改登陆信息
        Logininfo oldLogininfo = logininfoMapper.loadByAll(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        //设置会以前的id - 进行修改
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }

    //手机注册
    @Override
    public void phoneRegister(Map<String, String> map) {
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String pwd = map.get("pwd");
        String repwd= map.get("repwd");
        //校验
        //1.空值
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode) || StringUtils.isEmpty(pwd) ||
                StringUtils.isEmpty(repwd)){
            throw new BusinessException("信息不能为空");
        }
        //判断两次密码是不是一样
        if (!pwd.equals(repwd)){
            throw new BusinessException("两次密码不一样");
        }
        //手机验证码是否过期是否正确
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if (obj==null){
            throw new BusinessException("手机验证过期");
        }
        if (!phoneCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("手机验证错误");
        }


        //将数据添加到数据库

        User user=map2User(map);

        Logininfo logininfo =user2Logininfo(user);

        logininfoMapper.save(logininfo);

        user.setLogininfoId(logininfo.getId());


        userMapper.save(user);



    }


    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setDisable(true);
        logininfo.setType(1);
        return logininfo;
    }

    private User map2User(Map<String,String> map) {
        User user = new User();
        String phone = map.get("phone");
        user.setUsername(phone);
        user.setPhone(phone);
        //生成32位盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密加盐
        String byMd5 = Md5Utils.encrypByMd5(map.get("pwd") + salt);
        user.setPassword(byMd5);
        user.setSalt(salt);
        user.setState(1);


        return user;
    }
    //邮箱注册
    @Override
    public void emailRegister(Map<String,String> map) throws MessagingException {
        String email = map.get("email");
        String password = map.get("password");
        String repassword = map.get("repassword");


        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password) || StringUtils.isEmpty(repassword) ){
            throw new BusinessException("信息不能为空");

        }
        //判断邮箱是否被注册
        User user =userMapper.loadByEmail(email);
        if (user !=null){
            throw new BusinessException("该邮箱已被注册，请直接登录");
        }

        if(!password.equals(repassword)){
            throw new BusinessException("两次密码不一样，请重新输入");
        }

        //将数据添加到数据库

        User user1 = map2User1(map);

        Logininfo logininfo =user2Logininfo1(user1);

        logininfoMapper.save(logininfo);

        user1.setLogininfoId(logininfo.getId());


        userMapper.save(user1);
        //3.发邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        helper.setFrom("1924562332@qq.com");
        helper.setSubject("店铺激活邮件");
        User user2 = userMapper.loadByAll(user1.getId());
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h1>你的账号已经注册!!! ><a href='http://127.0.0.1:8080/user/active/"+user2.getId()+"'>点击该链接激活</a>",true);
        //店铺管理员


        helper.setTo(user2.getEmail());
        //发送
        javaMailSender.send(mimeMessage);


    }

    private User map2User1(Map<String,String> map) {
        User user = new User();
        String email = map.get("email");
        user.setUsername(email);
        user.setEmail(email);
        //生成32位盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密加盐
        String byMd5 = Md5Utils.encrypByMd5(map.get("password") + salt);
        user.setPassword(byMd5);
        user.setSalt(salt);
        user.setState(0);


        return user;
    }

    private Logininfo user2Logininfo1(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setDisable(false);
        logininfo.setType(1);
        return logininfo;
    }
    //邮箱用户激活
    @Override
    public void userAudit(Long id) {
        User user = userMapper.loadByAll(id);
        user.setState(1);
         userMapper.update(user);
        Logininfo logininfo = logininfoMapper.loadByAll(user.getLogininfoId());
         logininfo.setDisable(true);

        logininfoMapper.update(logininfo);


    }







}
